﻿using Dapper;
using EIP.Base.Models.Entities.System;
using EIP.Base.Models.Entities.WeChat;
using EIP.Base.Repository.Fixture;
using EIP.Common.Extension;
using EIP.Common.Log;
using EIP.Common.Message.DingTalk.Dto;
using EIP.Common.Message.Email.Dto;
using EIP.Common.Message.Sms.Dto;
using EIP.Common.Message.WebSite;
using EIP.Common.Message.WebSite.Dto;
using EIP.Common.Util;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using NLog;
using Senparc.Weixin;
using Senparc.Weixin.CommonAPIs;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Tea;
using Logger = EIP.Common.Log.Logger;

namespace EIP.Workflow.Logic.Imp
{
    public class WorkflowMessageLogic : IWorkflowMessageLogic
    {
        private readonly IHubContext<WebSiteHub> _hub;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hub"></param>
        /// <param name="messageLogic"></param>
        public WorkflowMessageLogic(IHubContext<WebSiteHub> hub)
        {
            _hub = hub;
        }

        /// <summary>
        /// 保存短信日志
        /// </summary>
        /// <param name="message"></param>
        public async Task SendSms(SendSmsInput input)
        {
            switch (input.Provide)
            {
                case 0:
                    break;
                case 2:
                    break;
                case 4://凌凯
                    foreach (var item in input.Phone.Split(','))
                    {
                        Dictionary<string, string> parameters = new Dictionary<string, string>();
                        parameters.Add("CorpID", ConfigurationUtil.GetSection("EIP_SMS:LingKai:CorpID"));
                        parameters.Add("Pwd", ConfigurationUtil.GetSection("EIP_SMS:LingKai:Pwd"));
                        parameters.Add("Mobile", item);
                        parameters.Add("Content", input.Message.Trim());
                        parameters.Add("Cell", "1");
                        string url = "https://sdk3.028lk.com:9988/BatchSend2.aspx";
                        var results = await RequestUtil.Get(url, parameters, "gb2312");
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 保存邮件日志
        /// </summary>
        /// <param name="message"></param>
        public void SendEmail(SendEmailInput message)
        {
            Logger logger = new Logger("SaveEmailLog");
            var ei = new EIPLogEventInfo(LogLevel.Info, "SaveEmailLog", "保存邮件日志");
            foreach (var item in message.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                ei.Properties[item.Name] = item.GetValue(message, null);
            logger.Log(ei);
        }

        /// <summary>
        /// 保存站内消息
        /// </summary>
        /// <param name="message"></param>
        public async Task SendWebSite(SendWebSiteInput message)
        {
            using (var fix = new SqlDatabaseFixture())
            {
                SystemMessageLog systemMessageLog = new SystemMessageLog()
                {
                    MessageLogId = message.MessageLogId,
                    Title = message.Title,
                    Message = message.Message,
                    ReceiverId = message.ReceiverId,
                    ReceiverName = message.ReceiverName,
                    ReceiverType = message.ReceiverType.ToShort(),
                    OpenType = message.OpenType,
                    OpenUrl = message.ReturnUrl,
                    CreateTime = DateTime.Now,
                    CustomerData = message.CustomerData,
                };
                await fix.Db.SystemMessageLog.InsertAsync(systemMessageLog);
                //查找接收人员
                foreach (var receiverId in message.ReceiverId.Split(','))
                {
                    var user = OnlineUsers.Users.FirstOrDefault(w => w.UserId == Guid.Parse(receiverId));
                    if (user != null)
                    {
                        await _hub.Clients.Client(user.ConnectionId).SendAsync("SendWebSiteMessage", JsonConvert.SerializeObject(systemMessageLog));
                    }
                }
                //通知人员
            }
        }

        /// <summary>
        /// 微信公众号
        /// </summary>
        /// <param name="input"></param>
        public async void SendOfficialAccount(SendOfficialAccountInput input)
        {
            //解析发送
            //获取需要发送用户的OpenId
            using (var fix = new SqlDatabaseFixture())
            {
                var userSql = $"select wu.openId,wu1.UserId from wechat_user wu left join wechat_user wu1 on wu.Unionid=wu1.Unionid where wu.Type = 1 and wu1.UserId in ({input.ReceiverId.InSql()}) ";
                var users = await fix.Db.Connection.QueryAsync<WeChatUser>(userSql);
                TemplateModel_MiniProgram miniProgram = null;
                if (input.MiniAppId.IsNotNullOrEmpty())
                {
                    miniProgram = new TemplateModel_MiniProgram
                    {
                        appid = input.MiniAppId,
                        pagepath = input.ReturnUrl
                    };
                }
                IDictionary<string, object> propertyDics = new Dictionary<string, object>();
                foreach (var item in input.Parameter)
                {
                    propertyDics.Add(item.Name, new TemplateDataItem("" + item.Value + "", item.Color));
                }

                foreach (var item in users)
                {
                    var result = ApiHandlerWapper.TryCommonApi(accessToken =>
                    {
                        string urlFormat = Config.ApiMpHost + "/cgi-bin/message/template/send?access_token={0}";
                        var submitData = new TemplateModel()
                        {
                            touser = item.OpenId,
                            template_id = input.Code,
                            url = input.ReturnUrl,
                            miniprogram = miniProgram,
                            data = propertyDics,
                        };
                        return CommonJsonSend.Send(accessToken, urlFormat, submitData, timeOut: Config.TIME_OUT);
                    }, input.OfficialAccountAppId);
                    if (result.errcode == ReturnCode.请求成功)
                    {

                    }
                }
            }
        }

        /// <summary>
        /// 钉钉
        /// </summary>
        /// <param name="input"></param>
        public async Task SendDingTalk(SendDingTalkInput input)
        {
            //解析发送
            using (var fix = new SqlDatabaseFixture())
            {
                //获取token
                AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateClient();
                AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest getAccessTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest()
                {
                    AppKey = ConfigurationUtil.GetSection("DingTalk:AppKey"),
                    AppSecret = ConfigurationUtil.GetSection("DingTalk:AppSecret"),
                };
                try
                {
                    var accessToken = client.GetAccessToken(getAccessTokenRequest);
                    //Post调用
                    foreach (var item in input.ReceiverId.Split(','))
                    {
                        var dingTalkUser = await fix.Db.DingTalkUser.FindAsync(f => f.UserId == Guid.Parse(item));
                        if (dingTalkUser != null&&dingTalkUser.DingTalkUserId.IsNotNullOrEmpty())
                        {
                            //调用发送
                            var sendResult = await RequestUtil.Post($"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={accessToken.Body.AccessToken}", new
                            {
                                agent_id = ConfigurationUtil.GetSection("DingTalk:AgentId"),
                                userid_list = dingTalkUser.DingTalkUserId,
                                msg = new
                                {
                                    msgtype = input.ReturnUrl.IsNotNullOrEmpty() ? "link" : "text",
                                    text = new
                                    {
                                        content = input.Message
                                    },
                                    link = new
                                    {
                                        messageUrl = input.ReturnUrl,
                                        title = input.Title,
                                        text = input.Message,
                                        picUrl = "@lALOACZwe2Rk"
                                    },
                                }
                            });
                        }
                    }

                }
                catch (TeaException err)
                {
                    if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                    {
                        // err 中含有 code 和 message 属性，可帮助开发定位问题
                    }
                }
                catch (Exception _err)
                {
                    TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                    if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                    {
                        // err 中含有 code 和 message 属性，可帮助开发定位问题
                    }
                }
            }
        }

        public static AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client(config);
        }
    }
}